package checkers.server.logic.classes;

import java.util.ArrayList;

import checkers.server.logic.classes.network.NetLayer;

public class GameContext {

	private NetLayer layer;
	private RegistrationManager registrator;
	private Logger log;
	private static GameContext gameContext;
	private boolean initialized;
	private ArrayList<Game> games;
	private ArrayList<Player> players;
	
	private GameContext() {
		initialized = false;
	}
	
	public static GameContext getInstance() {
		if (gameContext == null) {
			gameContext = new GameContext();
		}
		return gameContext;
	}
	
	void initializeGameContext(NetLayer layer, Logger log) throws Exception {
		if (initialized == true) {
			throw new Exception("Double initialization");
		}
		registrator = new RegistrationManager();
		games = new ArrayList<Game>();
		players = new ArrayList<Player>();
		this.layer = layer;
		this.log = log;
		initialized = true;
	}
	
	public void startServer() throws Exception {
		if (initialized == false) {
			throw new Exception("Not initialized");
		}
		layer.startListening();
	}

	public RegistrationManager getRegistrator() {
		return registrator;
	}

	public Logger getLogger() {
		return log;
	}
	
	public NetLayer getNetlayer() {
		return layer;
	}

	public ArrayList<Game> getAvailibleGames() {
		ArrayList<Game> rgame = new ArrayList<>();
		for (Game game : games) {
			if (!game.checkStart()) {
				rgame.add(game);
			}
		}
		return rgame;
	}

	public void addGame(Game game) {
		games.add(game);
	}
	
	public void addPlayer(Player player) {
		players.add(player);
	}
	
	public Player getPlayerById(int id) {
		for (Player player : players) {
			if (player.getId() == id) {
				return player;
			}
		}
		return null;
	}

	public Game getGameById(int id) {
		for (Game game : games) {
			if (game.getId() == id) {
				return game;
			}
		}
		return null;
	}
	
}
